<template>
  <div>
    <div class="container" v-if="!showUnitdetail">
      <div class="container-search">
        <!-- <div class="container-search-top"></div> -->
        <div class="container-search-bottom">
          <!-- 筛选条件 -->
          <div class="search">
            <div class="search-item">
              <el-input
                v-model="params.name"
                placeholder="请输入单位名称"
                clearable
                maxlength="25"
                class="search-input"
              />
            </div>
            <div class="search-item">
              <el-cascader
                v-model="params.region"
                placeholder="请选择行政区划"
                :options="options"
                filterable
                clearable
                @change="handlerregion"
                :props="areaprops"
              />
            </div>
            <div class="search-item">
              <el-select
                v-model="params.typeId"
                placeholder="请选择单位类型"
                clearable
                class="search-input"
              >
                <el-option
                  v-for="dict in unittypeList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </div>
            <div class="search-item">
              <el-select
                v-model="params.levelId"
                placeholder="请选择单位级别"
                clearable
                class="search-input"
              >
                <el-option
                  v-for="dict in unitlevelList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </div>
            <div class="search-item">
              <el-select
                v-model="params.industryId"
                placeholder="请选择所属行业"
                clearable
                class="search-input"
              >
                <el-option
                  v-for="dict in supervisorList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </div>
            <div class="search-item">
              <el-button type="primary" @click="getalarmList(true)"
                ><img src="@/assets/images/search.png" alt="" /> 搜索</el-button
              >
              <el-button color="#eff3ff" :dark="true" @click="reset"
                ><img src="@/assets/images/reset.png" alt="" />
                <span style="color: #6d98fd">重置 </span>
              </el-button>
            </div>
            <div class="search-item">
              <el-select
                v-model="params.alarmType"
                placeholder="请选择预警类型"
                clearable
                class="search-input"
              >
                <el-option
                  v-for="dict in sourceList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </div>
            <div class="search-item">
              <el-date-picker
                v-model="params.dateRange"
                type="daterange"
                align="right"
                range-separator="至"
                start-placeholder="预警开始日期"
                end-placeholder="预警结束日期"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
              />
            </div>
          </div>
        </div>
      </div>

      <div class="container-table">
        <!-- 表格筛选 -->
        <div style="display: flex; justify-content: space-between">
          <div class="filter">
            <div
              class="filter-item"
              :class="activeindex === '' ? 'active' : ''"
              @click="handlerfilter('')"
            >
              <img
                src="@/assets/images/all.png"
                alt=""
                srcset=""
                v-if="activeindex === ''"
              />
              <img src="@/assets/images/blueall.png" alt="" srcset="" v-else />
              <div class="item-text">全部 （{{ all }}）</div>
            </div>
            <div
              class="filter-item"
              :class="activeindex === 0 ? 'active' : ''"
              @click="handlerfilter(0)"
            >
              <img
                src="@/assets/images/waitcheck.png"
                alt=""
                srcset=""
                v-if="activeindex === 0"
              />
              <img
                src="@/assets/images/bluewaitcheck.png"
                alt=""
                srcset=""
                v-else
              />

              <div class="item-text">未处置 （{{ not }}）</div>
            </div>
            <div
              class="filter-item"
              :class="activeindex === 1 ? 'active' : ''"
              @click="handlerfilter(1)"
            >
              <img
                src="@/assets/images/check.png"
                alt=""
                srcset=""
                v-if="activeindex === 1"
              />
              <img
                src="@/assets/images/bluecheck.png"
                alt=""
                srcset=""
                v-else
              />

              <div class="item-text">已处置 （{{ yes }}）</div>
            </div>
          </div>
          <div class="rule" @click="handlertooltip">
            <img src="@/assets/images/doubt.png" alt="" />
            <span style="cursor: pointer"> 预警规则 </span>
          </div>
          <div class="tooltip" v-if="showtooltip">
            <div class="contenttext">
              <div class="contenttext-close" @click="closetooltip">⨉</div>
              <div class="contenttext-content1">
                <div class="content-item">
                  <div class="content-tab">临期未整改</div>
                  <div class="content-text">
                    整改期截至前10天未完成的单位（整改期40天）
                  </div>
                </div>
                <div class="content-item">
                  <div class="content-tab">超期未整改</div>
                  <div class="content-text">整改期未整改完成的单位；</div>
                </div>
                <div class="content-item">
                  <div class="content-tab">临期未检查</div>
                  <div class="content-text">
                    检查期前30天未检查的单位；（单位一年一检）
                  </div>
                </div>
                <div class="content-item">
                  <div class="content-tab">超期未检查</div>
                  <div class="content-text">逾期未检查的单位</div>
                </div>
              </div>
            </div>
            <div class="triangle"></div>
          </div>
        </div>
        <!-- 表格数据 -->
        <el-table
          v-loading="loading"
          :data="alarmList"
          border
          height="52vh"
          :header-cell-style="{ 'text-align': 'center' }"
          @sort-change="sortChange"
        >
          <el-table-column
            label="操作"
            :show-overflow-tooltip="true"
            width="150"
            :resizable="false"
          >
            <template #default="{ row }">
              <div class="table-operate">
                <span class="detail" @click="handleOperate('detail', row)"
                  >详情</span
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="单位名称"
            prop="name"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="预警类型"
            prop="institutionType"
            :show-overflow-tooltip="true"
            align="center"
          >
            <template #default="{ row }">
              <div class="contenttext-content">
                <div
                  class="content-item"
                  v-if="row.alarmTypeName == '临期未整改'"
                >
                  <div class="content-tab" style="background-color: #ff7f00">
                    临期未整改
                  </div>
                </div>
                <div
                  class="content-item"
                  v-if="row.alarmTypeName == '超期未整改'"
                >
                  <div class="content-tab" style="background-color: #ff2c2c">
                    超期未整改
                  </div>
                </div>
                <div
                  class="content-item"
                  v-if="row.alarmTypeName == '临期未检查'"
                >
                  <div
                    class="content-tab"
                    style="background-color: #fff6a9; color: #ff6c2b"
                  >
                    临期未检查
                  </div>
                </div>
                <div
                  class="content-item"
                  v-if="row.alarmTypeName == '超期未检查'"
                >
                  <div
                    class="content-tab"
                    style="background-color: #ffc3a9; color: #ff6c2b"
                  >
                    超期未检查
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="区域范围"
            prop="areaName"
            width="300"
            :show-overflow-tooltip="true"
          >
          </el-table-column>

          <el-table-column
            label="预警说明"
            prop="alarmDescription"
            :show-overflow-tooltip="true"
          >
          </el-table-column>

          <el-table-column
            label="预警时间"
            prop="alarmDate"
            :show-overflow-tooltip="true"
            sortable="custom"
          >
            <template #default="{ row }">
              {{ row.alarmDate || "--" }}
            </template>
          </el-table-column>

          <el-table-column
            label="处置状态"
            prop="checkStatus"
            :show-overflow-tooltip="true"
            width="120"
            sortable="custom"
          >
            <template #default="{ row }">
              <div class="contenttext-content">
                <div class="content-item" v-if="row.checkStatus == 0">
                  <div
                    class="content-tab"
                    style="background-color: #fbdec8; color: #feab58"
                  >
                    未处置
                  </div>
                </div>
                <div class="content-item" v-if="row.checkStatus == 1">
                  <div
                    class="content-tab"
                    style="background-color: #f9c7c7; color: #fd6666"
                  >
                    已处置
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <pagination
          class="pagination"
          :total="total"
          v-model:page="params.pageNum"
          v-model:limit="params.pageSize"
          @pagination="getalarmList"
        />
      </div>
    </div>

    <!-- 详情 -->
    <Unitdetail
      v-if="showUnitdetail"
      ref="Unitdetailref"
      v-model:showUnitdetail="showUnitdetail"
    ></Unitdetail>
    <!-- 检查记录详情 -->
    <el-dialog
      v-model="showdialog"
      width="700px"
      append-to-body
      class="dialogBox"
    >
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <img src="@/assets/images/title-card.png" alt="" />
          <div class="header-title">预警详情</div>
        </div>
        <div class="taskdetail">
          <div class="detail-top">
            <div class="detial-text">
              <div class="detial-title">
                <div class="title-top">
                  <div class="title">{{ detaildata.name }}</div>
                </div>
                <div class="title-bottom">
                  <div class="bottom-item">
                    <div class="item-title">预警时间：</div>
                    <div class="item-content">
                      {{ detaildata.alarmDate }}
                    </div>
                  </div>
                  <div class="bottom-item">
                    <div class="item-title">预警内容：</div>
                    <div class="item-content">
                      {{ detaildata.alarmDescription }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="detail-img">
              <img
                src="@/assets/images/unfinishprogress.png"
                alt=""
                v-if="detaildata.checkStatus == 0"
              />
              <img
                src="@/assets/images/finishprogress.png"
                alt=""
                v-if="detaildata.checkStatus == 1"
              />
            </div>
          </div>
          <div class="detail-bottom">
            <div class="top">
              <div class="top-title">监测状态：</div>
              <div>{{ detaildata.checkStatus == 0 ? "未处置" : "已处置" }}</div>
            </div>
            <div class="top">
              <div class="top-title">解除原因：</div>
              <div>
                {{
                  detaildata.disposalContent ? detaildata.disposalContent : "-"
                }}
              </div>
            </div>
          </div>
          <div class="detail-btn">
            <el-button type="primary" style="width: 100%" @click="showunitdtl">
              查看单位详情
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import Card from "@/components/Card";
import Unitdetail from "../erp/unit/unitdetail";
import {
  getalarmMonitorlist,
  selectTaskAlarmMonitorListCount,
} from "@/api/warning/warning";
import { getDictsApi, getAreaList } from "@/api/dict";
import { getToken } from "@/utils/auth";
import { ElMessage, ElMessageBox } from "element-plus";
const { proxy } = getCurrentInstance();

// 搜索参数
let params = reactive({
  pageNum: 1,
  pageSize: 20,
  name: "",
  typeId: "",
  levelId: "",
  industryId: "",
  checkStatus: "",
  region: [],
  dateRange: [],
  alarmType: "",
  provinceId: "",
  cityId: "",
  zoneId: "",
  streetId: "",
});

// 总数
const total = ref(0);

//行政区划数据
let options = ref([]);
const areaprops = {
  lazy: true,
  checkStrictly: true,
  lazyLoad(node, resolve) {
    const { level } = node;
    let datas = [];
    setTimeout(() => {
      let code = 1;
      if (level != 0) {
        code = node.data.value;
      }
      getAreaList({ pid: code }).then((response) => {
        if (response.data && response.data.length) {
          datas = response.data.map((item, i) => ({
            value: item.value,
            label: item.label,
            leaf: level >= 2,
            // disabled: level == 0, // 这里可以设置为 true 来禁用这个选项
          }));
        } else {
          datas = [];
        }
        resolve(datas);
      });
    }, 200);
  },
};

// 表格加载效果
const loading = ref(false);
//检查列表
const alarmList = ref([]);
//时间选择

// 单位类型下拉
const unittypeList = ref([]);
// 单位级别下拉
const unitlevelList = ref([]);
// 所属行业下拉
const supervisorList = ref([]);
//任务来源下拉
const sourceList = ref([]);
// 详情弹窗的显隐
let showdialog = ref(false);
// 单位详情弹窗的显隐
let showUnitdetail = ref(false);
//单位详情组件的引用
const Unitdetailref = ref(null);
//选中的项
let activeindex = ref("");
//提示的显隐
let showtooltip = ref(false);

//上传的状态
let uploadstatus = ref("add");
let replaceindex = ref(0);
let indexToReplace = ref(0);
const format = (percentage) =>
  percentage === 100 ? "上传中……" : `${percentage}%`;
const uploadSuccess = (res) => {
  console.log("chenggon", res);
  if (res.code == 200) {
    ElMessage.success("图片上传成功！");
    isUpload.value = false;
    if (uploadstatus.value == "add") {
      picList.value.push(res.data);
    } else {
      console.log("zhixing");
      picList.value.splice(indexToReplace.value, 1, res.data);
      uploadstatus.value = "add";
    }
  } else {
    isUpload.value = false;
    proxy.$modal.msgError("文件上传失败！");
  }
};

function beforeUpload(file) {
  console.log("file", file);
  if (file.name.length > 50) {
    ElMessage.error(`文件名过长！最多只能上传50个文字的文件名文件！`);
    return false;
  }
  isUpload.value = true;
}
/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}

/**
 * @description: 表格数据接口
 */
let waittaskList = ref([]);
let finishtaskList = ref([]);
const getalarmList = (flag) => {
  if (flag == true) {
    params.pageNum = 1;
    params.pageSize = 20;
  }
  loading.value = true;
  if (params.dateRange) {
    if (params.dateRange.length > 0) {
      params.startDate = params.dateRange[0] + " 00:00:00";
      params.endDate = params.dateRange[1] + " 23:59:59";
    }
  } else {
    params.dateRange = [];
    params.startDate = "";
    params.endDate = "";
  }
  getalarmMonitorlist(
    { pageNum: params.pageNum, pageSize: params.pageSize },
    params
  ).then((res) => {
    alarmList.value = res.rows;
    total.value = res.total;
    loading.value = false;
    getAlarmMonitorCount();
  });
};
/**
 * @description: 预警统计
 */
let all = ref(0);
let not = ref(0);
let yes = ref(0);
const getAlarmMonitorCount = () => {
  let countparams = JSON.parse(JSON.stringify(params));
  // 删除 taskStatus 属性
  delete countparams.checkStatus;
  selectTaskAlarmMonitorListCount(
    { pageNum: params.pageNum, pageSize: params.pageSize },
    countparams
  ).then((res) => {
    all.value = res.data.all;
    not.value = res.data.not;
    yes.value = res.data.yes;
  });
};

/**
 * @description: 打开预警提示
 */
const handlertooltip = () => {
  showtooltip.value = true;
};
/**
 * @description: 关闭预警提示
 */
const closetooltip = () => {
  showtooltip.value = false;
};

/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
const sortChange = (column) => {
  console.log("column", column);
  if (column.prop == "alarmDate" && column.order) {
    params.sortField = "a.create_time";
  } else if (column.prop == "checkStatus" && column.order) {
    params.sortField = "a.check_status";
  } else {
    params.sortField = "";
  }
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else if (column.order === "ascending") {
    params.sortOrder = "ASC"; // 排序或倒序
  } else {
    params.sortOrder = "";
  }
  getalarmList();
};

/**
 * @description: 重置
 */
const reset = () => {
  Object.assign(params, {
    pageNum: 1,
    pageSize: 20,
    name: "",
    typeId: "",
    levelId: "",
    industryId: "",
    alarmType: "",
    checkStatus: "",
    region: [],
    dateRange: [],
    provinceId: "",
    cityId: "",
    zoneId: "",
    streetId: "",
    startDate: "",
    endDate: "",
  });
  activeindex.value = "";
  getalarmList();
};

/**
 * @description: tab操作
 */
const handlerfilter = (index) => {
  activeindex.value = index;
  params.checkStatus = index;
  getalarmList();
};

/**
 * @description: 联级处理省市区操作
 * @param {String} type 类型
 */
const handlerregion = (value) => {
  if (value) {
    switch (value.length) {
      case 1:
        params.provinceId = value[0];
        break;
      case 2:
        params.provinceId = value[0];
        params.cityId = value[1];
        break;
      case 3:
        params.provinceId = value[0];
        params.cityId = value[1];
        params.zoneId = value[2];
        break;
      case 4:
        params.provinceId = value[0];
        params.cityId = value[1];
        params.zoneId = value[2];
        params.streetId = value[3];
        break;

      default:
        break;
    }
  } else {
    params.region = [];
    params.provinceId = null;
    params.cityId = null;
    params.zoneId = null;
    params.streetId = null;
  }
};
/**
 * @description: 重置为初始状态
 */
const resetall = () => {
  //导入分页数据
  ImporttableList.value = [];
  //正常的数据
  normalData.value = [];
  //重复的数据
  repeatData.value = [];
  //异常的数据
  abnormalData.value = [];
  importsuccess.value = false;
};
/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
let detaildata = ref({});
const handleOperate = async (type, row) => {
  switch (type) {
    case "detail":
      showdialog.value = true;
      detaildata.value = row;
      break;

    default:
      break;
  }
};
/**
 * @description: 单位详情展示
 */
const showunitdtl = () => {
  showdialog.value = false;
  showUnitdetail.value = true;
  nextTick(() => {
    Unitdetailref.value.handleDetailInfo(detaildata.value);
  });
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  await getDictsApi("institution_type").then((res) => {
    //单位类型下拉
    if (res.code === 200) {
      unittypeList.value = res.data;
    }
  });
  await getDictsApi("institution_industry_type").then((res) => {
    //行业主管下拉
    if (res.code === 200) {
      supervisorList.value = res.data;
    }
  });
  await getDictsApi("fkwz_institution_level_type").then((res) => {
    //单位级别下拉
    if (res.code === 200) {
      unitlevelList.value = res.data;
    }
  });
  await getDictsApi("task_alarm_type").then((res) => {
    //预警类型下拉
    if (res.code === 200) {
      sourceList.value = res.data;
    }
  });
}

onMounted(() => {
  getalarmList();
  getAlarmMonitorCount();
  getDicts();
});
</script>

<style scoped lang="scss">
.container {
  position: relative;
  .container-search {
    margin-bottom: 12px;
    .container-search-bottom {
      background-color: #ffffff;
      border-radius: 10px;
      padding: 15px 15px 15px 15px;
    }
  }

  .container-button {
    position: absolute;
    top: 15px;
    right: 15px;
    img {
      margin-right: 6px;
      margin-top: 2px;
    }
  }
  .container-table {
    position: relative;
    background-color: #ffffff;
    border-radius: 10px;
    padding: 15px 15px 15px 15px;
    .filter {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 460px;
      background: #ffffff;
      box-shadow: 0px 1px 4px 0px rgba(51, 51, 51, 0.1);
      border-radius: 20px;
      font-size: 14px;
      padding: 2px;
      margin-bottom: 10px;
      .filter-item {
        cursor: pointer;
        display: flex;
        align-items: center;
        padding: 10px 20px;
        border-radius: 20px;
        color: #7eb7fe;
        img {
          height: 16px;
          margin-right: 2px;
        }
      }
      .active {
        background-color: #4aa1fe;
        color: #ffffff;
      }
    }
    .rule {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #3276fd;
      img {
        margin-right: 5px;
      }
    }
    .tooltip {
      position: absolute;
      top: -90px;
      right: 106px;
      display: flex;
      align-items: center;
      z-index: 10;
      .triangle {
        width: 0;
        height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-bottom: 7.5px solid #ffffff; /* 边长为100px时，高度为边长的正弦值乘以2/3 */
        transform: rotate(90deg) translateY(7px);
      }
      .contenttext {
        box-shadow: 0px 6px 20px 0px rgba(0, 0, 0, 0.3);
        max-width: 800px;
        padding: 20px;
        background-color: #fff;
        transform: translateX(-5px);
        border-radius: 10px;
        .contenttext-close {
          color: #4d88fd;
          text-align: right;
          cursor: pointer;
        }
        .contenttext-content1 {
          font-size: 14px;
          .content-item {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            .content-tab {
              padding: 6px 10px;
              background: #ff7f00;
              border-radius: 4px;
              margin-right: 5px;
              color: #fff;
            }
          }
          .content-item:nth-child(2) {
            .content-tab {
              background: #ff2c2c;
            }
          }
          .content-item:nth-child(3) {
            .content-tab {
              background: #fff6a9;
              color: #ff6c2b;
            }
          }
          .content-item:nth-child(4) {
            .content-tab {
              background: #ffc3a9;
              color: #ff6c2b;
            }
          }
        }
      }
    }
    .check-tab {
      display: flex;
      .tab-item {
        display: flex;
        .tab {
          padding: 4px 12px;
          margin-right: 10px;
        }
        .tab-time {
          width: 110px;
          padding: 4px 12px;
        }
      }
      .orange {
        color: #ef8e4d;
        background-color: #f7e3c3;
        border-radius: 5px;
      }
      .green {
        color: #60cba7;
        background-color: #bbeddc;
        border-radius: 5px;
      }
    }
    .contenttext-content {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 12px;
      .content-item {
        display: flex;
        align-items: center;

        .content-tab {
          padding: 3px 5px;
          border-radius: 4px;
          margin-right: 5px;
          color: #fff;
        }
      }
    }
  }
}
.taskdetail {
  padding: 20px;
  .detail-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .detial-text {
      display: flex;
      .detial-title {
        display: flex;
        flex-direction: column;
        .title-top {
          display: flex;
          align-items: center;
          margin-bottom: 25px;
          .title {
            font-size: 16px;
            font-weight: 600;
            color: #000000;
            margin-right: 50px;
          }
          .tabs {
            display: flex;
            .tab {
              padding: 5px 10px;
              color: #ffffff;
              margin-right: 10px;
            }
            .tab:nth-child(1) {
              background-color: #088ef8;
            }
            .tab:nth-child(2) {
              background-color: #e2a802;
            }
          }
        }
        .title-bottom {
          font-size: 14px;
          .bottom-item {
            display: flex;
            align-items: baseline;
            margin-bottom: 25px;
            .item-content {
              width: 80%;
            }
          }
        }
      }
    }
  }
  .detail-bottom {
    display: flex;
    background-color: #ebf2ff;
    flex-wrap: wrap;
    font-size: 14px;
    .top {
      display: flex;
      width: 40%;
      margin-top: 20px;
      align-items: baseline;
      .top-title {
        flex-shrink: 0;
      }
    }
    .top:last-child {
      width: 90%;
      margin-bottom: 20px;
    }
  }
  .detail-btn {
    padding: 20px;
  }
}
</style>

<style>
.ImportdialogBox {
  .el-pagination {
    margin-top: 20px;
    justify-content: center;
  }
}
</style>
